<?php

namespace App\Http\Controllers\Recommend;

use App\Http\Controllers\Controller;
use App\Http\Requests\Recommend\ApppageRectplRequest;
use App\Models\Application\Apppage;
use App\Models\Application\Muticolumn;
use App\Models\Application\Pagetpl;
use App\Models\Application\Paneltpl;
use App\Models\Entity\Column\Collist;
use App\Models\Recommend\ApppageRectpl;
use App\Models\Recommend\ApppageRectplArea;
use App\Repositories\Recommend\ApppageRectplRepository;
use Encore\Admin\Controllers\ModelForm;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Flash;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Storage;
use Response;
use DB;

class ApppageRectplController extends Controller
{
    use ModelForm;

    /** @var  ApppageRectplRepository */
    private $apppageRectplRepository;

    public function __construct(ApppageRectplRepository $apppageRectplRepo)
    {
        $this->apppageRectplRepository = $apppageRectplRepo;
    }

    /**
     * Display a listing of the ApppageRectpl.
     *
     * @return Response
     */
    public function index()
    {
        return Admin::content(function (Content $content) {

            $content->header(__('recommend.apppage_rectpls.index_header'));
            $content->description(__('recommend.apppage_rectpls.index_description'));

            $content->body($this->grid());
        });
    }

    /**
     * Show the form for creating a new ApppageRectpl.
     *
     * @return Response
     */
    public function create()
    {
        return Admin::content(function (Content $content) {

            $content->header(__('recommend.apppage_rectpls.create_header'));
            $content->description(__('recommend.apppage_rectpls.create_description'));

            $content->body($this->form());

        });
    }

    /**
     * Store a newly created ApppageRectpl in storage.
     *
     * @param ApppageRectplRequest $request
     *
     * @return Response
     */
    public function store(ApppageRectplRequest $request)
    {
        $input = $request->all();

        $apppageRectpl = $this->apppageRectplRepository->create($input);

        Flash::success(__('recommend.apppage_rectpls.saved_success'));

        return Input::get('_previous_') ? redirect(Input::get('_previous_')) : redirect(route('recommend.apppage_rectpls.index'));

    }

    /**
     * Display the specified ApppageRectpl.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function show($id)
    {
        $apppageRectpl = $this->apppageRectplRepository->findWithoutFail($id);

        if (empty($apppageRectpl)) {
            Flash::error(__('recommend.apppage_rectpls.not_found'));

            return redirect(route('recommend.apppage_rectpls.index'));
        }

        return view('recommend.apppage_rectpls.show')->with('apppageRectpl', $apppageRectpl);

    }

    /**
     * Show the form for editing the specified ApppageRectpl.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function edit($id)
    {
        $apppageRectpl = $this->apppageRectplRepository->findWithoutFail($id);

        if (empty($apppageRectpl)) {
            Flash::error(__('recommend.apppage_rectpls.not_found'));

            return redirect(route('recommend.apppage_rectpls.index'));
        }
        return Admin::content(function (Content $content) use ($id, $apppageRectpl) {

            $content->header(__('recommend.apppage_rectpls.edit_header'));
            $content->description(__('recommend.apppage_rectpls.edit_description'));

            $content->body($this->form()->edit($id));
            // $content->row(view('recommend.apppage-rectpls.edit', ['data_type' => $apppageRectpl->data_type, 'data_id' => $apppageRectpl->data_id]));

        });
    }

    /**
     * Update the specified ApppageRectpl in storage.
     *
     * @param  int              $id
     * @param ApppageRectplRequest $request
     *
     * @return Response
     */
    public function update($id, ApppageRectplRequest $request)
    {
        $apppageRectpl = $this->apppageRectplRepository->findWithoutFail($id);

        if (empty($apppageRectpl)) {
            Flash::error(__('recommend.apppage_rectpls.not_found'));

            return redirect(route('recommend.apppage_rectpls.index'));
        }
        $input = $request->all();

        $apppageRectpl = $this->apppageRectplRepository->update($input, $id);

        Flash::success(__('recommend.apppage_rectpls.updated_success'));

        return Input::get('_previous_') ? redirect(Input::get('_previous_')) : redirect(route('recommend.apppage_rectpls.index'));
    }

    /**
     * Remove the specified ApppageRectpl from storage.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function destroy($id)
    {
        // 根据 `,` 判断传递过来的是单个id还是多个id
        if (substr_count($id, ',') >= 1) {
            $id = explode(",", $id);
        }

        // 如果是数组则进行批量删除
        if (is_array($id)) {
            if ($flag = $this->apppageRectplRepository->batchDelete('id', $id)) {

                return response()->json(['message' => __('recommend.apppage_rectpls.deleted_success'), 'status' => $flag]);
            } else {
                return response()->json(['message' => __('base.deleted.error'), 'status' => $flag]);
            }
        }

        $apppageRectpl = $this->apppageRectplRepository->findWithoutFail($id);

        if (empty($apppageRectpl)) {
            Flash::error(__('recommend.apppage_rectpls.not_found'));

            return redirect(route('recommend.apppage_rectpls.index'));
        }

        if ($flag = $this->apppageRectplRepository->delete($id)) {

            return response()->json(['message' => __('recommend.apppage_rectpls.deleted_success'), 'status' => $flag]);
        } else {
            return response()->json(['message' => __('base.deleted.error'), 'status' => $flag]);
        }
    }

    /**
     * [form description]
     * @return {[type]} [description]
     */
    protected function form()
    {
        return Admin::form(ApppageRectpl::class, function (Form $form) {

            $form->display('id', 'ID');
            $form->text('name', '名称');
            $form->text('title', '推荐位标题');
            $form->text('subtitle', '推荐位副标题');
            // $form->select('data_type', '数据类型')->options(array(
            //     1 => '栏目',
            //     2 => '栏目列表',
            // ))->default('1')
            //     ->load('data_id', route('application.collist_datas.datas.resources'), 'id', 'title');
            // $muticolumns = Muticolumn::orderBy('listorder', 'asc')->pluck('title', 'id');
            // $form->select('data_id', '数据')->options($muticolumns);
            $form->text('area', '区位编号');
            $pagetpls = Pagetpl::pluck('title', 'id');
            $form->select('pagetpl_id', '页面模板选择')->options($pagetpls);
            $paneltpls = Paneltpl::pluck('title', 'id');
            $form->select('paneltpl_id', '模板编号')->options($paneltpls);
            $form->text('param', '参数');
            $form->textarea('description', '描述');

            $form->display('created_at', __('base.created_at'));
            $form->display('updated_at', __('base.updated_at'));

        });
    }

    /**
     * [grid description]
     * @return {[type]} [description]
     */
    protected function grid()
    {

        return Admin::grid(ApppageRectpl::class, function (Grid $grid) {
            // 考虑是否需要scope和排序
            // $grid->model()->orderBy('listorder', 'asc');

            // // 添加按钮
            // if (!\Gate::check('recommend.apppage_rectpls.create')) {
            //     $grid->disableCreation();
            // }

            // // 编辑和删除按钮
            // $grid->actions(function ($actions) {
            //     // 编辑按钮
            //     if (!\Gate::check('recommend.apppage_rectpls.edit')) {
            //         $actions->disableEdit();
            //     }
            //     // 删除按钮
            //     if (!\Gate::check('recommend.apppage_rectpls.destroy')) {
            //         $actions->disableDelete();
            //     }
            // });

            // // 导出按钮
            // if (!\Gate::check('recommend.apppage_rectpls.export')) {
            //     $grid->disableExport();
            // }

            // // 批量操作
            // $grid->tools(function ($tools) {
            //     $tools->batch(function ($batch) {
            //         // 批量删除按钮
            //         if (!\Gate::check('recommend.apppage_rectpls.batch_destroy')) {
            //             $batch->disableDelete();
            //         }
            //     });
            // });

            // 添加按钮
            if (Admin::user()->cannot('recommend.apppage_rectpls.create')) {
                $grid->disableCreation();
            }

            // 编辑和删除按钮
            $grid->actions(function ($actions) {
                $id           = $actions->getKey();
                $pagetplId    = $actions->row->pagetpl_id;
                $paneltplId   = $actions->row->paneltpl_id;
                $paneltplName = Paneltpl::where(['id' => $paneltplId])->value('name');

                // 编辑按钮
                if (Admin::user()->cannot('recommend.apppage_rectpls.edit')) {
                    $actions->disableEdit();
                }
                // 删除按钮
                if (Admin::user()->cannot('recommend.apppage_rectpls.destroy')) {
                    $actions->disableDelete();
                }

                // 跳转推荐位数据
                // $actions->append('<a href=' . route('recommend.apppage_rectpl_datas.index', ['apppage_rectpl_id' => $id, 'pagetpl_id' => $pagetplId, 'paneltpl_id' => $paneltplId]) . ' onclick="" title="数据编辑">&nbsp;&nbsp;数据编辑</a>');
                // 区位数据编辑
                $actions->append('<a href=' . route('recommend.apppage_rectpl_areas.index', ['apppage_rectpl_id' => $id, 'pagetpl_id' => $pagetplId, 'paneltpl_id' => $paneltplId]) . ' onclick="" title="数据编辑">&nbsp;&nbsp;数据编辑/</a>');
                $actions->append('<a href=' . route('recommend.apppage_rectpls.paneltpl.view', ['apppage_rectpl_id' => $id, 'paneltpl_name' => $paneltplName]) . ' onclick="" title="数据模板编辑">&nbsp;&nbsp;数据模板编辑/</a>');

            });

            // 导出按钮
            if (Admin::user()->cannot('recommend.apppage_rectpls.export')) {
                $grid->disableExport();
            }

            // 批量操作
            $grid->tools(function ($tools) {
                $tools->batch(function ($batch) {
                    // 批量删除按钮
                    if (Admin::user()->cannot('recommend.apppage_rectpls.batch_destroy')) {
                        $batch->disableDelete();
                    }
                });
            });
            $grid->column('id', 'ID')->sortable();
            $grid->column('name', '名称')->sortable();
            $grid->column('title', '推荐位标题')->sortable();
            $grid->column('subtitle', '推荐位副标题')->sortable();
            $grid->column('pagetpl.title', '页面模板')->sortable();
            $grid->column('area', '区位编号')->sortable();
            $grid->column('paneltpl.title', '模板编号')->sortable();
            $grid->column('param', '参数')->sortable();
            $grid->column('description', '描述')->sortable();

            /**
             * 过滤处理
             */
            $grid->filter(function ($filter) {
                // // 禁用id查询框
                // $filter->disableIdFilter();
                // 页面
                $tmpPagetpls = Paneltpl::pluck('title', 'id');
                $filter->equal('paneltpl_id', '页面')->select($tmpPagetpls);
                $filter->like('name', '名称');

            });
        });
    }

    /**
     * ajax根据数据类型获取数据
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    public function getReasourceData($dataId, Request $request)
    {
        $datas = [];
        // 根据传递的数据类型ID获取不同的数据列表
        if ($dataId === '1') {
            $datas = Muticolumn::orderBy('listorder', 'asc')->get(['title', 'id'])->toArray();
        } elseif ($dataId === '2') {
            $datas = Collist::orderBy('listorder', 'asc')->get(['title', 'id'])->toArray();
        } elseif ($dataId === '3') {
            $datas = ApppageRectpl::get(['title', 'id'])->toArray();
        }
        return response()->json(['content' => $datas, 'status' => true]);
    }
    /**
     * 进入模板视图
     * @param  [type]  $rectplId     [description]
     * @param  [type]  $paneltplName [description]
     * @param  Request $request      [description]
     * @return [type]                [description]
     */
    public function paneltplView($rectplId, $paneltplName, Request $request)
    {

        DB::beginTransaction();
        try {
            // 是否检测区位信息是否拥有
            $apppageRectpl = ApppageRectpl::with(['pagetpl'])->find($rectplId);
            if (empty($apppageRectpl)) {
                Flash::error(__('application.apppage_rectpls.not_found'));
                return redirect(route('application.apppage_rectpls.index'));
            }
            // 获取栏目推荐区位信息定义
            $apppageRectplAreas = ApppageRectplArea::where(['apppage_rectpl_id' => $rectplId])->get();
            if (empty($apppageRectplAreas->first())) {
                // 获取panel模板信息
                $paneltpl       = Paneltpl::where(['id' => $paneltplId])->first();
                $panelAreaDatas = [];
                $areas          = json_decode($paneltpl->areas, true);
                if (!empty($areas)) {
                    foreach ($areas as $key => $area) {
                        $panelAreaDatas[$key]['apppage_rectpl_id'] = intval($rectplId);
                        $panelAreaDatas[$key]['pagetpl_id']        = intval($apppageRectpl->pagetpl_id);
                        $panelAreaDatas[$key]['paneltpl_id']       = intval($apppageRectpl->paneltpl_id);
                        $panelAreaDatas[$key]['area']              = $area;
                        $panelAreaDatas[$key]['data']              = null;
                        $panelAreaDatas[$key]['created_at']        = date('Y-m-d H:i:s', time());
                    }
                }
                $result = DB::table('apppage_rectpl_areas')->insert($panelAreaDatas);
                DB::commit();
            }
        } catch (Exception $e) {
            DB::rollback();
            dd($e->getMessage());
        }
        $data                        = [];
        $data['apppage_rectpl_id']   = $rectplId;
        $data['apppage_rectpl_name'] = $apppageRectpl->name;
        $data['template_name']       = $paneltplName;
        $data['pagetpl_name'] = $apppageRectpl->pagetpl->name;
        if (view()->exists('application.paneltpls.templates.' . $paneltplName)) {
            // 这一行使用
            return view('application.paneltpls.templates.' . $paneltplName, $data);
        } else {
            Flash::error(__('模板文件未找到，请检查是否已上传模板文件'));
            return redirect(route('recommend.apppage_rectpls.index'));
        }
    }

}
